package cn.besbing.server.controllers.other;


import cn.besbing.model.entities.primary.AssessView;
import cn.besbing.model.entities.primary.AssessViewExample;
import cn.besbing.model.entities.primary.CProjLoginSample;
import cn.besbing.server.service.primary.AssessServiceImpl;
import cn.besbing.server.service.primary.PrimaryCustomServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RequestMapping("extenalapi")
@Controller
public class ExtenalApi {

    private static String bingUrl = "http://cn.bing.com/HPImageArchive.aspx?format=js&n=1&pid=hp&idx=-1";


    @Autowired
    private PrimaryCustomServiceImpl customService;

    @Autowired
    private AssessServiceImpl assessService;


    /**
     * 获取必应每日壁纸
     * 调用/extenalapi/geturl
     * @throws IOException
     */
    @GetMapping("geturl")
    public  void getBingBackPic() throws IOException, URISyntaxException {
        RestTemplate restTemplate = getrestTemplate();
        URI uri = new URI(bingUrl);
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(exchange.getBody());System.out.println(jsonObject);
    }

    public RestTemplate getrestTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return new RestTemplate(factory);
    }

    /*
    public static void main(String[] args) throws URISyntaxException {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        RestTemplate restTemplate = new RestTemplate(factory);
        URI uri1 = new URI(bingUrl);
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(uri1, HttpMethod.POST, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(exchange.getBody());
        JSONArray jsonArray = jsonObject.getJSONArray("images");
        JSONObject j = jsonArray.getJSONObject(0);
        String url = "https://cn.bing.com" + j.get("url").toString();
        System.out.println(url);
    }
     */

    /**
     *
     * @param cuserid
     * @param projectOrTaskid
     * @return
     * projectOrTaskid=A-200331-0103-01
     */
    @GetMapping("assessByCustomer")
    public String assessByCustomer(String cuserid, String projectOrTaskid, Model model){
        /*
        判断cuserid是否存在，taskid或project是否与cuserid一致，如果不一致，直接返回404
        */
        /*
        List<Map<String, Object>> checkList = new ArrayList<Map<String, Object>>();
        String sql = "select h.BILLNO project,tb.taskcode taskcode,h.CREATOR cuserid,nrt.RP_REPORT_NAME reportype " +
                " from QC_COMMISSION_H h , QC_TASK_h th , NC_REPORT_TYPE nrt , QC_TASK_B tb " +
                " where h.CREATOR = '" + cuserid + "' and h.REPORTFORMAT = nrt.PK_REPORT_TYPE " +
                " and (h.BILLNO = '" + projectOrTaskid + "' or tb.taskcode = '" + projectOrTaskid + "') and h.BILLNO = th.billno and th.pk_task_h = tb.pk_task_h " +
                " order by tb.taskcode asc" ;
        checkList = customService.selectList(sql);
        */
        /*
        if (checkList.size() < 1)
            return "errors/406";
        if (checkList.size() > 1 && !"成套".equals(checkList.get(0).get("reportype").toString().trim()) )
            return "errors/406";
        //NC外链满意度评价
        //return "errors/401";
        //String url = "?taskid=" + projectOrTaskid;
        model.addAttribute("taskid",projectOrTaskid);
        return "pages/lims/limsweb/assessByCustomer";
        */
        AssessViewExample assessViewExample = new AssessViewExample();
        assessViewExample.setOrderByClause("taskcode asc");
        assessViewExample.setDistinct(true);
        AssessViewExample.Criteria criteria = assessViewExample.createCriteria();
        if(StringUtils.isNotBlank(cuserid)){
            criteria.andCuseridEqualTo(cuserid);
        }
        if(StringUtils.isNotBlank(projectOrTaskid)){
            if (projectOrTaskid.length() > 14)
                criteria.andTaskcodeEqualTo(projectOrTaskid);
            else
                criteria.andProjectEqualTo(projectOrTaskid);
        }
        List<AssessView> assessList = assessService.selectByExample(assessViewExample);
        /*
        判断结果的合法性，taskid或project是否与cuserid一致，如果不一致，直接返回406
        */
        if (assessList.size() < 1)
            return "errors/406";
        model.addAttribute("assessList",assessList.get(0));
        return "pages/lims/limsweb/assessByCustomer";
    }


}
